package com.android.smsmessing.services;

import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;
import android.provider.Contacts;
import android.provider.Contacts.People;
import android.provider.Contacts.Phones;

import com.android.smsmessing.model.PeopleVO;

public class PeopleService {

	private  static PeopleService instance = null;
	
	public static PeopleService getInstance(){
		if(instance == null){
			instance = new PeopleService();
		}
		return instance;
	}
	/**
	 * 获取全部联系人
	 * 
	 * @param context
	 *            上下文
	 * @return 联系人列表
	 */
	public  ArrayList<PeopleVO> getAllPeople(Context context) {
		ArrayList<PeopleVO> result = new ArrayList<PeopleVO>();
		final Cursor people = context.getContentResolver().query(
				Contacts.People.CONTENT_URI, null, null, null, null);
		while (people.moveToNext()) {
			String name = people.getString(people
					.getColumnIndexOrThrow(Contacts.People.NAME));
			String phone = people.getString(people
					.getColumnIndexOrThrow(Contacts.People.NUMBER));
			// 用名字作为key,phone作为value
			PeopleVO p = new PeopleVO();
			p.name = name;
			p.mobile = phone;
			result.add(p);
		}
		people.close();
		return result;
	}

	/**
	 * 通过电话号码查询用户姓名
	 * 
	 * @param context
	 * @return 联系人姓名
	 */
	public  String getPeopleNameByNumber(Context context,String number) {
		String result = null;
		String[] projection = new String[] { Contacts.Phones.DISPLAY_NAME };
		Cursor personCur = context.getContentResolver().query(
				Phones.CONTENT_URI, projection,
				Phones.NUMBER + "=?", new String[] { number },
				Phones.DISPLAY_NAME + " ASC");
		//如果存在那么获取姓名
		if (personCur.moveToFirst()) {
			result = personCur
					.getString(personCur
							.getColumnIndexOrThrow(Contacts.Phones.DISPLAY_NAME));
		}
		return result;
		
	}
}
